import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../repository/dto/list_dto.dart';
import 'home_vm.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final HomeViewModel homeViewModel = HomeViewModel();
  // List<BannerItemData> bannerList = [];

  RefreshController refreshController = RefreshController();

  @override
  void initState() {
    super.initState();
    homeViewModel.getBanner();
    homeViewModel.getAllList();
    // initBanner();
  }

  // void initBanner() async {
  //   bannerList = await HomeViewModel.getBanner() ?? [];
  //   print(bannerList);
  //   setState(() {});
  // }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => homeViewModel,
      child: Scaffold(
        body: SafeArea(
          child: SmartRefresher(
            // 下拉刷新和上拉加载更多
            controller: refreshController,
            enablePullDown: true,
            enablePullUp: true,
            header: ClassicHeader(),
            footer: ClassicFooter(),
            onRefresh: () async {
              await homeViewModel.getAllList();
              refreshController.refreshCompleted();
            },
            onLoading: () async {
              await homeViewModel.getAllList(true);
              refreshController.loadComplete();
            },
            child: SingleChildScrollView(
              child: Column(children: [_banner(), _list()]),
            ),
          ),
        ),
      ),
    );
  }

  Widget _banner() {
    return Consumer<HomeViewModel>(
      builder: (context, vm, child) {
        return SizedBox(
          height: 200,
          width: double.infinity,
          child: Swiper(
            itemCount: vm.bannerList?.length ?? 0,
            autoplay: true,
            indicatorLayout: PageIndicatorLayout.NONE,
            control: SwiperControl(),
            pagination: SwiperPagination(),
            itemBuilder: (context, index) {
              return Container(
                height: 150,
                color: Colors.yellow,
                child: Image.network(
                  vm.bannerList?[index]?.imagePath ?? '',
                  fit: BoxFit.cover,
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _list() {
    return Consumer<HomeViewModel>(
      builder: (context, vm, child) {
        return ListView.builder(
          itemCount: vm.listData?.length ?? 0,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _listItem(vm, index);
          },
        );
      },
    );
  }

  Widget _listItem(HomeViewModel vm, int index) {
    ListItemData item = vm.listData![index]!;
    return GestureDetector(
      onTap: () {
        print('点击了${vm.listData?[index]?.title}');
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(10, 0, 10, 10),
        padding: EdgeInsets.fromLTRB(10, 5, 10, 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: Colors.amber, width: 1),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                ClipOval(
                  child: Image.network(
                    'https://img2024.cnblogs.com/blog/35695/202509/35695-20250923174722171-270282128.jpg',
                    width: 30,
                    height: 30,
                    fit: BoxFit.cover,
                  ),
                ),
                SizedBox(width: 5),
                Text(item.chapterName),
                Expanded(child: Container()),
                Text(item.niceShareDate),
                SizedBox(width: 10),
                item.type == 1
                    ? Text('置顶', style: TextStyle(color: Colors.blue))
                    : Container(),
              ],
            ),
            SizedBox(height: 5),
            Text(item.title, style: TextStyle(fontSize: 14)),
            SizedBox(height: 5),
            SizedBox(height: 5),
            Row(
              children: [
                Text(
                  item.author.isEmpty ? item.shareUser : item.author,
                  style: TextStyle(color: Colors.green),
                ),
                Expanded(child: Container()),
                IconButton(
                  onPressed: () async {
                    if (item.collect) {
                      await vm.unCollect(item.id, index);
                    } else {
                      await vm.collect(item.id, index);
                    }
                  },
                  icon: item.collect
                      ? Icon(Icons.favorite, color: Colors.red)
                      : Icon(Icons.favorite_border, color: Colors.grey),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
